package com.huchengrui.guesssong2

import android.content.Context
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.provider.MediaStore
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.huchengrui.guesssong2.SetPicture.setPicture
import com.huchengrui.guesssong2.databinding.ActivityGuessingBinding
import java.net.URL

class Guessing : AppCompatActivity() {
    private lateinit var binding: ActivityGuessingBinding
    private val mediaPlayer = MediaPlayer()
    private var songname:String?=null
    private var path:String?=null
    private var starttime = 0
    private val songName = mutableListOf<String>()
    private val songPath = mutableMapOf<String,String>()
    private var millis = 3000L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        path = intent.getStringExtra("path")
        millis =getSharedPreferences("data", Context.MODE_PRIVATE).getLong("millis", 3000L)
        binding = ActivityGuessingBinding.inflate(layoutInflater)
        setContentView(binding.root)
//        setPicture(binding.imageView, URL(getSharedPreferences("data", MODE_PRIVATE).getString(
//            "imageUrl",
//            "https://api.lazy.ink/img-phone/"
//        )))
        binding.imageView.setImageBitmap(BitmapFactory.decodeFile("${this.externalCacheDir!!.absolutePath}/background.jpg"))
        val selection = "${MediaStore.Audio.Media.DATA} like ?"
        val cursor = contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
            selection, arrayOf("$path%"), null
        )
        if (cursor != null) {
            val pathIndex=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)
            val nameIndex=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)
            while (cursor.moveToNext()) {
                var name = cursor.getString(nameIndex)
                name = if (name.contains(" - ")) {
                    name.substring(name.indexOf(" - ") + 3, name.lastIndexOf('.'))
                } else {
                    name.substring(0, name.lastIndexOf('.'))
                }
                songName.add(name)
                songPath[name] = cursor.getString(pathIndex)
            }
        }
        cursor?.close()
        initMediaPlayer()
        binding.playButton.setOnClickListener {
            initMediaPlayer()
            binding.textView.text = ""
            binding.textInputEditText.setText("")
            playMillis(millis)
        }
        binding.confirmButton.setOnClickListener {
            if (songname != null) {
                val inputString = binding.textInputEditText.text.toString()
                if (songname!!.length >= 6) {
                    val length = inputString.length
                    if (length < 6) {
                        binding.textView.setText(R.string.not_enough_characters)
                    } else if ( songname!!.lowercase().contains(inputString.lowercase())) {
                        correctAnswer()
                    } else {
                        binding.textView.setText(R.string.wrong)
                    }
                } else {
                    if (songname.equals(inputString, true)) {
                        correctAnswer()
                    } else {
                        binding.textView.setText(R.string.wrong)
                    }
                }
            }
        }
        binding.replayButton.setOnClickListener {
            mediaPlayer.seekTo(starttime)
            playMillis(millis)
        }
        binding.answerButton.setOnClickListener {
            binding.textView.text = getString(R.string.answer, songname)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.guessing,menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        millis = when (item.itemId) {
            R.id.easy -> 5000L
            R.id.medium -> 3000L
            R.id.hard -> 1000L
            else -> millis
        }
        val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
        editor.putLong("millis", millis)
        editor.apply()
        return true
    }

    override fun onDestroy() {
            super.onDestroy()
            mediaPlayer.stop()
            mediaPlayer.release()
    }

    private fun initMediaPlayer() {
        mediaPlayer.reset()
        songname = songName.random()
        val duration = mediaPlayer.run {
            setDataSource(songPath[songname])
            prepare()
            duration
        }
        starttime = (0..duration - 5000).random()
        mediaPlayer.seekTo(starttime)
    }

    private fun playMillis(length: Long) {
        binding.playButton.isClickable = false
        binding.replayButton.isClickable = false
        mediaPlayer.start()
        Handler(mainLooper).postDelayed({
            mediaPlayer.pause()
            binding.playButton.isClickable = true
            binding.replayButton.isClickable = true
        }, length)
    }

    private fun correctAnswer() {
        binding.textView.setText(R.string.right)
    }
}